package xyz.blushyes.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.util.Strings;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import xyz.blushyes.dao.CacheTestDao;
import xyz.blushyes.entity.CacheTest;
import xyz.blushyes.service.CacheTestService;

import static xyz.blushyes.constant.CacheConst.CACHE_PREFIX;

@Service
@RequiredArgsConstructor
public class CacheTestServiceImpl extends ServiceImpl<CacheTestDao, CacheTest> implements CacheTestService {
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public int notCache(int number) {
        return lambdaQuery()
                .eq(CacheTest::getNumber, number)
                .oneOpt()
                .map(CacheTest::getId)
                .orElse(-1);
    }

    @Override
    public int simpleCache(int number) {
        // 首先查缓存
        String key = CACHE_PREFIX + number;
        String cache = stringRedisTemplate.opsForValue().get(key);

        // 如果缓存不为空，则直接返回
        if (!Strings.isBlank(cache)) {
            return Integer.parseInt(cache);
        }

        // 否则从数据库查找
        int id = lambdaQuery().eq(CacheTest::getNumber, number)
                .oneOpt()
                .map(CacheTest::getId)
                .orElse(-1);

        // 并存入Redis
        stringRedisTemplate.opsForValue().set(key, String.valueOf(id));
        return id;
    }
}

